package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.Inputbill;
import com.tianxin.workbao.workBao.bean.InputbillDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.DateUtilLast;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.StringUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.WhereCondition;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Request;

/**
 * Created by hacker on 2017/7/25.
 */

public class InputProvide extends BaseDataProvide {
    private Integer mPage=1;
    private List<Inputbill> mInputList;
    private int dataType;
    private UpdateListViewListener mUpdateListViewListener;
    private InputbillDao inputDao;
    private boolean isStatistic = false;
    private boolean isGetData = true;

    public InputProvide(Context context, UpdateListViewListener listener) {
        super(context);
        mUpdateListViewListener = listener;
        inputDao = mGreenDaoHelper.getDaoSession().getInputbillDao();
    }

    private void getFromDb(int page) {
        Date start = null;
        Date end = null;
        Date date = new Date();
        switch (dataType) {
            case Constant.TODAY_DATA:
                start = DateUtilLast.getStartTime();
                end = DateUtilLast.getEndTime();
                break;
            case Constant.WEEK_DATA:
                start = DateUtilLast.getStartTimeOfDay(DateUtilLast.getFirstDayOfWeek(date));
                end = DateUtilLast.getEndTimeOfDay(DateUtilLast.getLastDayOfWeek(date));
                break;
            case Constant.MONTH_DATA:
                start = DateUtilLast.getStartTimeOfDay(DateUtilLast.getFirstDayOfMonth(date));
                end = DateUtilLast.getEndTimeOfDay(DateUtilLast.getLastDayOfMonth(date));
                break;
            case Constant.SEASON_DATA:
                start = DateUtilLast.getStartTimeOfDay(DateUtilLast.getFirstDayOfQuarter(date));
                end = DateUtilLast.getEndTimeOfDay(DateUtilLast.getLastDayOfQuarter(date));
                break;
            case Constant.YEAR_DATA:
                start = DateUtilLast.getStartTimeOfDay(DateUtilLast.getCurrYearFirst());
                end = date;
                break;
        }


        Query<Inputbill> query = inputDao.queryBuilder().where(InputbillDao.Properties.Isis.eq(1))
                .where(InputbillDao.Properties.Addtime.gt(start))
                .where(InputbillDao.Properties.Addtime.lt(end))
                .offset((page - 1) * Constant.COAL_PAGE_SIZE)
                .limit(Constant.COAL_PAGE_SIZE)
                .build();
        mInputList = query.list();
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject object = new JSONObject(responseObj.toString());
                    int status = object.getInt(Constant.RESPONSE_STATUS);
                    String information = object.getString(Constant.RESPONSE_INFO);
                    if (status > 0) {
                        if (isGetData == false) {
                            mUpdateListViewListener.showMessage("ok");
                            return;
                        }
                        if (mInputList != null && !mInputList.isEmpty()) {
                            mInputList.clear();
                        }
                        String dataJson = object.getString(Constant.RESPONSE_DATA);
                        if (dataJson != null || dataJson.length() > 2) {
                            try {
                                if (dataJson.startsWith("[") && dataJson.endsWith("]") && dataJson.length() > 3) {
                                    mInputList = JSON.parseArray(dataJson,Inputbill.class);
                                    refreshUI();
                                    saveToDb(mInputList);
                                } else {
                                    mInputList.add(JSON.parseObject(dataJson,Inputbill.class));
                                    refreshUI();
                                    if (isStatistic == false) {
                                        saveToDb(mInputList);
                                    }
                                }
                            } catch (Exception e) {
                                mUpdateListViewListener.showMessage("input To Bean Error :类型转换出错" + e.getMessage());
                            }

                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    } else {
                        if (isGetData == false) {
                            mUpdateListViewListener.showMessage("failure" + information);
                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    }
                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode() + ":" + exception.getEmsg().toString());
                } else {
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    /**
     * true save data to databases
     *
     * @param obj
     */
    private void saveToDb(Object obj) {
        if (obj instanceof List) {
            for (int i = 0; i < mInputList.size(); i++) {
                inputDao.insertOrReplace(mInputList.get(i));
            }
        } else {
            inputDao.insertOrReplace((Inputbill) obj);
        }
    }


    /**
     * update the coal data  from server
     */
    private void updateFromServer() {
        mUpdateListViewListener.showProgress();
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        map.put("dataType", dataType + "");
        map.put("page", mPage + "");
        RequestParams params = new RequestParams(map);
        CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getInputBillsUrl(), params), getDisposeDataHandle());
    }

    public void getDatas(int type, int page) {
        mPage = page;
        dataType = type;
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            getFromDb(page);
            refreshUI();
        } else {
            updateFromServer();
        }
    }

    @Override
    public void refreshUI() {
        if (mPage > 1) {
            mUpdateListViewListener.onLoadMoreData(mInputList);
        } else {
            mUpdateListViewListener.onRefreshData(mInputList);
        }
    }


    public void getNoSampling(Integer supplycpid, Integer coaltypeid) {
        mPage = 1;
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        } else {
            String url = URL.getNoSamplingUrl();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("supplycpid", supplycpid + "");
            map.put("coaltypeid", coaltypeid + "");
            RequestParams params = new RequestParams(map);
            Request postRequest = CommonRequest.createPostRequest(url, params);
            CommonOkHttpClient.post(postRequest, getDisposeDataHandle());
        }
    }

    public void search(String query) {
        if (mInputList != null) {
            mInputList.clear();
            mPage = 1;
        }
        String where = "";
        if (StringUtils.isHasChineseChar(query)) {
            where = "salecompany like '%" + query + "%' or coaltype like '%" + query + "%' ";
        } else if (StringUtils.isNumber(query)) {
            where = "carnumber like '%" + query + "%' ";
        } else {
            mUpdateListViewListener.showMessage("输入有错！");
        }
        if (where.length() < 1) return;
        Query<Inputbill> userQuery = inputDao.queryBuilder()
                .where(new WhereCondition.StringCondition(where))
                .orderDesc(InputbillDao.Properties.Addtime)
                .build();
        mInputList = userQuery.list();
        refreshUI();
    }

    public void getStatistic(Integer dataType) {
        isStatistic = true;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            String url = URL.getCoalStatisticUrl();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("type", dataType + "");
            RequestParams params = new RequestParams(map);
            Request postRequest = CommonRequest.createPostRequest(url, params);
            CommonOkHttpClient.post(postRequest, getDisposeDataHandle());
        } else {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        }
    }

    public void getNoOauthDatas(int oauthStatus, int page) {
        isStatistic = false;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            String url = URL.getInNoOauthBillUrl();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("page", page + "");
            map.put("oauth", oauthStatus + "");
            RequestParams params = new RequestParams(map);
            Request postRequest = CommonRequest.createPostRequest(url, params);
            CommonOkHttpClient.post(postRequest, getDisposeDataHandle());
        } else {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        }
    }

    public void oauth(int id) {
        isGetData = false;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            String url = URL.getInOauthUrl();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("id", id + "");
            RequestParams params = new RequestParams(map);
            Request postRequest = CommonRequest.createPostRequest(url, params);
            CommonOkHttpClient.post(postRequest, getDisposeDataHandle());
        } else {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        }
    }
}
